<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>HTML5模拟微信聊天界面</title>
    <style>
        /**重置标签默认样式*/
        * {
            margin: 0;
            padding: 0;
            list-style: none;
            font-family: '微软雅黑'
        }
        #container {
            width: 450px;
            background: #eee;
            height:500px;
            overflow-y: auto;
            overflow-x:hidden;
            margin: 40px auto 0;
            position: relative;
            box-shadow: 20px 20px 55px #777;
        }
        .header {
            background: #000;
            width:430px;
            height: 60px;
            z-index:10000;
            position:fixed;
            top:0px;
            color: #fff;
            line-height: 34px;
            font-size: 20px;
            padding: 0 10px;
        }
        .footer {
            width: 430px;
            height: 50px;
            background: #666;
            top:500px;
            position:fixed;
            bottom: 0;
            padding: 10px;
        }
        .footer input {
            /*width: 275px;*/
            width: 250px;
            height: 45px;
            outline: none;
            font-size: 20px;
            text-indent: 10px;
            position: absolute;
            border-radius: 6px;
            right: 80px;
        }
        .footer span {
            display: inline-block;
            width: 62px;
            height: 48px;
            background: #ccc;
            font-weight: 900;
            line-height: 45px;
            cursor: pointer;
            text-align: center;
            position: absolute;
            right: 10px;
            border-radius: 6px;
        }
        .footer span:hover {
            color: #fff;
            background: #999;
        }
        #user_face_icon {
            display: inline-block;
            background: red;
            width: 60px;
            height: 60px;
            border-radius: 30px;
            position: absolute;
            bottom: 6px;
            left: 14px;
            cursor: pointer;
            overflow: hidden;
        }
        img {
            width: 60px;
            height: 60px;
        }
        .content {
            font-size: 20px;
            width: 435px;
            margin-bottom:100px; margin-top:40px;
            padding: 5px;
        }
        .content li {
            margin-top: 10px;
            padding-left: 10px;
            width: 412px;
            display: block;
            clear: both;
            overflow: hidden;
        }
        .content li img {
            float: left;
        }
        .content li span{
            background: #7cfc00;
            padding: 10px;
            border-radius: 10px;
            float: left;
            margin: 6px 10px 0 10px;
            max-width: 310px;
            border: 1px solid #ccc;
            box-shadow: 0 0 3px #ccc;
        }
        .content li img.imgleft {
            float: left;
        }
        .content li img.imgright {
            float: right;
        }
        .content li span.spanleft {
            float: left;
            background: #fff;
        }
        .content li span.spanright {
            float: right;
            background: #7cfc00;
        }
        span{
            word-break: break-all;
        }
    </style>
    {load href="__JS__jquery.min.js"}
    {load href="__PLUGINS__layui/layui.js"}
    {load href="__PLUGINS__layui/css/layui.css"}
    <script>
        function datahtml(data,touid) {
            html='';

            $.each(data, function(commentIndex, comment){
                if(comment.userid==touid){
                    if(comment.type==1){

                        html += '<li id="'+comment.id+'"><img src="__ROOT__{$user.head_portrait}"><span class="spanleft"><img src="'+comment.image+'"></span></li>'

                    }else if(comment.type==2){

                        html += '<li id="'+comment.id+'"><img src="__ROOT__{$user.head_portrait}" class="imgleft spanleft"><span class="spanleft"><button class="amr"  sw="0" onclick="amrplay('+"'"+comment.content+"'"+')">[语音]</button></span></li>'

                    }else{
                        html += '<li id="'+comment.id+'"><img src="__ROOT__{$user.head_portrait}" class="imgleft spanleft"><span class="spanleft">'+comment.content+'</span></li>'
                    }

                }else{

                    if(comment.type==1){
                        html += ' <li id="'+comment.id+'"><img src="__ROOT__{$user2.head_portrait}" class="imgright spanright"><span class="spanright"><img src="'+comment.image+'"></span></li>'

                    }else if(comment.type==2){
                        html += ' <li id="'+comment.id+'"><img src="__ROOT__{$user2.head_portrait}" class="imgright spanright"><span class="spanright"><button class="amr"  sw="0" onclick="amrplay('+"'"+comment.content+"'"+')">[语音]</button></span></li>'
                    }else{
                        html += ' <li id="'+comment.id+'"><img src="__ROOT__{$user2.head_portrait}" class="imgright spanright"><span class="spanright">'+comment.content+'</span></li>'
                    }


                }
            });
            return html;
        }
        layui.use('layer', function(){
            //浏览器显示未读
            function xianshi(n){

                var titleInit = document.title, isShine = true;

                setTimeout(function() {
                    var title = document.title;
                    if (isShine == true) {
                        if(/新/.test(title) == false){
                            document.title = '【你有'+n+'新消息】';
                        }else{
                            document.title = '【　　　　　】';
                        }
                    }else{
                        document.title = titleInit;
                    }
                    titleinit();
                }, 500);
                var titleinitTime;
                function titleinit() {

                    titleinitTime = setTimeout(function() {
                        var title = document.title;
                        if (isShine == true) {
                            if(/新/.test(title) == false){
                                document.title = '【你有'+n+'新消息】';
                            }else{
                                document.title = '【　　　　　】';
                            }
                        }else{
                            document.title = titleInit;
                        }
                        titleinit();
                    }, 500);
                }
                window.onfocus = function() {
                    isShine = false;
                };
                window.onblur = function() {
                    isShine = true;
                };

                // for IE
                document.onfocusin = function() {
                    isShine = false;
                };
                document.onfocusout = function() {
                    isShine = true;
                };

            }




            window.onload = function(){
                onGetMessage();

                var arrIcon = ['http://www.xttblog.com/icons/favicon.ico','http://www.xttblog.com/wp-content/uploads/2016/03/123.png'];
                var url = "{:url('usertalk/onchatdata')}";
                var num = 0;     //控制头像改变    1自己，0客服
                var iNow = "{$count-1}";    //用来累加改变左右浮动
                var icon = document.getElementById('user_face_icon').getElementsByTagName('img');
                var btn = document.getElementById('btn');
                var text = document.getElementById('image');
                var imgs = "{:checkpath(_imgUrl('1')._user($uid)['img'])}";
                var content = document.getElementsByTagName('ul')[0];
                var span = content.getElementsByTagName('span');
                var img = content.getElementsByTagName('img');
                var imgu ="{$user.head_portrait}";
                icon.onclick = function(){
                    if(num==0){
                        this.src = arrIcon[1];
                        num = 1;
                    }else if(num==1){
                        this.src = arrIcon;
                        num = 0;
                    }
                }
                btn.onclick = function(){
                    if(text.value ==''){
                        layer.msg('不能发送空消息');
                        // alert('不能发送空消息');
                    }else {
                        var neirong = text.value;
                        var userid ="{$uid}";
                        var touserid ="{$touid}";

                        if(text.value.indexOf('disk/')!=-1){
                            var type = 1;
                        } else {
                            var type = 0;
                        }
                        var url = "{$url}";
                        $.ajax({
                            url: url + '/apis/home/privatechat/addtalk',
                            type: 'post',
                            headers: {"authorization":"{$token}"},
                            data: {userid:userid,touserid:touserid,content:neirong,type:type},
                            dataType: 'json',
                            success: function (result) {
                                // 成功
                                /*callback(result)*/

                                if (result.code == 400) {
                                    layer.msg(result.msg);
                                }

                            },
                            error: function (err) {

                                /*_log(JSON.stringify(err))*!/
                                if(err.status == 200){
                                    callback(err)
                                }else{
                                    _log('服务器错误');
                                }*/

                                onGetMessage();
                                /* content.innerHTML += '<li ><img src="'+imgs+'" class="imgright"><span class="spanright"><a href="' + text.value +'")}" target="_blank"><img src="' + text.value +'"></a></span></li>';
                                 if(text.value.indexOf('disk/')!=-1){
                                     content.innerHTML += '<li id='+end+'><img src="'+imgs+'" class="imgright"><span class="spanright"><a href="' + text.value +'")}" target="_blank"><img src="' + text.value +'"></a></span></li>';
                                 } else {
                                     content.innerHTML += '<li id='+end+'><img src="'+imgs+'" class="imgright"><span class="spanright">'+text.value+'</span></li>';
                                 }*/
                                text.value = '';
                                // 内容过多时,将滚动条放置到最底端
                                container.scrollTop=content.scrollHeight;
                            }
                        });

                        /*$.post('{:url('usertalk/addTalk')}',{userid:userid,touserid:touserid,content:neirong,type:type}, function(res) {
                            onGetMessage();
                            if (res.code==200) {
                                if(text.value.indexOf('disk/')!=-1){
                                    content.innerHTML += '<li id="'+res.id+'"><img src="'+imgs+'" class="imgright"><span class="spanright"><a href="' + text.value +'")}" target="_blank"><img src="' + text.value +'"></a></span></li>';
                                } else {
                                    content.innerHTML += '<li id="'+res.id+'"><img src="'+imgs+'" class="imgright"><span class="spanright">'+text.value+'</span></li>';
                                }




                                text.value = '';
                                // 内容过多时,将滚动条放置到最底端
                                container.scrollTop=content.scrollHeight;
                            }else{
                                layer.msg('发送失败');
                            }
                        },'json');*/



                    }
                }
            }


            function onGetMessage() {
                //msg.innerHTML+=context;
                document.getElementById("msg_end").scrollIntoView();
            }
            setTimeout(function(){
                var uid ="{$uid}";
                var ntouid ="{$touid}";
                var end=$('ul').find("li").last().attr('id');
                // console.log(end);return false;
                $.post('{:url('usertalk/shang')}',{uid:uid,touid:ntouid,first:end}, function(res) {
                    // console.log(res.weidu)
                    if(res.weidu>0){
                        xianshi(res.weidu);
                    }
                    // document.getElementById('main').innerHTML="";
                    // var html = '';
                    // html=datahtml(res.data,ntouid);
                    var html='';
                    html=datahtml(res.data,ntouid);
                    htmlm=$('#main').html();
                    $('#main').html(htmlm+html);
                    // $.each(res.data, function(commentIndex, comment){
                    //         if(comment.touid=="{$touid}"){

                    //             if(comment.type==1){

                    //                    html += '<li><img src="{$user.head_portrait}"><span class="spanleft"><img src="'+comment.image+'"></span></li>'

                    //             }else if(comment.type==2){

                    //                    html += '<li><img src="{$user.head_portrait}" class="imgleft spanleft"><span class="spanleft">语音</span></li>'

                    //             }else{
                    //                 html += '<li><img src="{$user.head_portrait}" class="imgleft spanleft"><span class="spanleft">'+comment.content+'</span></li>'
                    //             }

                    //         }else{

                    //             if(comment.type==1){
                    //                 html += ' <li><img src="'+imgs+'" class="imgright spanright"><span class="spanright"><img src="'+comment.image+'"></span></li>'

                    //             }else if(comment.type==2){
                    //               html += ' <li><img src="'+imgs+'" class="imgright spanright"><span class="spanright">'+comment.content+'</span></li>'
                    //             }else{
                    //               html += ' <li><img src="'+imgs+'" class="imgright spanright"><span class="spanright">'+comment.content+'</span></li>'
                    //             }


                    //         }
                    // });
                    // document.getElementById('main').innerHTML=html; //加载数据
                    // onGetMessage();
                    shuaxin();
                },'json');


            },1000);

            function shuaxin() {
                setTimeout(function(){
                    var uid ="{$uid}";
                    var ntouid ="{$touid}";
                    var end=$('ul').find("li").last().attr('id');
                    $.post('{:url('usertalk/shang')}',{uid:uid,touid:ntouid,first:end}, function(res) {
                        // console.log(res.weidu)
                        if(res.weidu>0){
                            xianshi(res.weidu);
                        }
                        var html='';
                        html=datahtml(res.data,ntouid);
                        htmlm=$('#main').html();
                        $('#main').html(htmlm+html);
                        // console.log(end)
                        // document.getElementById('main').innerHTML="";
                        // var html = '';
                        // html=datahtml(res.data,ntouid);
                        // $.each(res.data, function(commentIndex, comment){
                        //         if(comment.touid=="{$touid}"){

                        //             if(comment.type==1){

                        //                    html += '<li><img src="{$user.head_portrait}"><span class="spanleft"><img src="'+comment.image+'"></span></li>'

                        //             }else if(comment.type==2){

                        //                    html += '<li><img src="{$user.head_portrait}" class="imgleft spanleft"><span class="spanleft">语音</span></li>'

                        //             }else{
                        //                 html += '<li><img src="{$user.head_portrait}" class="imgleft spanleft"><span class="spanleft">'+comment.content+'</span></li>'
                        //             }

                        //         }else{

                        //             if(comment.type==1){
                        //                 html += ' <li><img src="'+imgs+'" class="imgright spanright"><span class="spanright"><img src="'+comment.image+'"></span></li>'

                        //             }else if(comment.type==2){
                        //               html += ' <li><img src="'+imgs+'" class="imgright spanright"><span class="spanright">'+comment.content+'</span></li>'
                        //             }else{
                        //               html += ' <li><img src="'+imgs+'" class="imgright spanright"><span class="spanright">'+comment.content+'</span></li>'
                        //             }


                        //         }
                        // });

                        // document.getElementById('main').innerHTML=html; //加载数据
                        // onGetMessage();
                        shuaxin();
                    },'json');


                },1000)
            }

        })

        function onGetMessage() {
            //msg.innerHTML+=context;
            document.getElementById("msg_end").scrollIntoView();
        }


    </script>
</head>
<body>
<div id="container">

    <div class="header" onClick="onGetMessage()">
        <!--<span style="float: left;"><img src="{$user.head_portrait}" alt="" width="60px" height="5px;"></span>-->
        <span style="float: right;margin-top:13px">{$user.name}</span>
    </div>
    <ul class="content" id="main">

        {volist name="data" id="v" key="k"}
        <li id="{$v.id}">
            <img {if condition="$v['touserid'] == $touid"} src="__ROOT__{:_user($uid)['img']}" class="imgright  spanright"{else /}src="__ROOT__{:_user($v.userid)['img']}" class="imgleft spanleft"{/if}>
            <span {if condition="$v['touserid'] == $touid"}class="spanright"{else /}class="spanleft"{/if}>{if condition="$v['type'] == 1"} <a href="__ROOT__{$v.content}" target="_blank"><img src="__ROOT__{$v.content}"></a>{elseif condition="$v['type'] == 2"/}<button class="amr"  sw="0" onclick="amrplay('{$v.content}')">[语音]</button>{else /}{$v.content}{/if}</span>
        </li>
        {/volist}

    </ul>

    <div class="footer">
        <div id="user_face_icon">
            <img src="__ROOT__{:_user($uid)['img']}" alt="" id="imgs">
        </div>
        <input id="image" type="text" placeholder="说点什么吧...">
        <span style="display:inline-block;background:#ccc;width:35px;right:338px" type="button" id="tubiao"> + </span>
        <span id="btn">发送</span>
    </div>
    <div id="msg_end" style="height:0px; overflow:hidden; margin-top:0px;"></div>
</div>
<script type="text/javascript">
    var wrap = document.getElementById('container');
    wrap.onscroll = function(){
        var t = wrap.scrollTop;
        if (t==0) {

            var first=$('ul').find("li").eq(0).attr('id');
            var uid ="{$uid}";
            var btouid ="{$touid}";
            $.post('{:url('usertalk/shang')}',{uid:uid,touid:btouid,first:first,type:1}, function(res) {
                if (res.code==200) {
                    if (res.total>0) {
                        var bhtml='';
                        bthml=datahtml(res.data,btouid);
                        mhtml=$('#main').html();
                        $('#main').html(bthml+mhtml);
                    }else{
                        layer.msg('没有更多了');
                    }
                }else{
                    layer.msg('获取失败');
                }
            },'json');
        }
    }
</script>
<script src="__STYLE__/amr.js/Libamr-2.2.5.min.js"></script>
<script src="__STYLE__/amr.js/RongIMVoice-2.2.5.min.js"></script>

<script type="text/javascript">
    function del(id){
        swal_del(id,"{:url('pdel')}")
    }
    /*
        初始化声音库
    */
    var RongIMVoice = RongIMLib.RongIMVoice;
    RongIMVoice.init();

    /*
        * play() 播放音频消息
        * 参数 voice 为 amr 格式的 base64
        * 示例: voice = "IyFBTVIKLNEafAAeef/hgmeAH8AD...";
    */

    function play(voice){
        if(voice){
            var duration = voice.length/1024;    // 音频持续大概时间(秒)
            RongIMVoice.preLoaded(voice, function(){
                RongIMVoice.play(voice,duration);
            });
        }else{
            console.error('请传入 amr 格式的 base64 音频文件');
        }
    }
    function stop(voice){
        if(voice){
            //停止播放
            RongIMLib.RongIMVoice.stop(voice);
        }else{
            console.error('请传入 amr 格式的 base64 音频文件');
        }
    }
    function amrplay(voice) {
        str=voice;
        if($(this).attr('sw')==1){
            stop(str);
            $(this).attr('sw',0);
        }else{
            play(str);
            $(this).attr('sw',1);
        }
    }
    $("#tubiao").click(function(){

        layer.open({
            type: 2,
            title: '上传图片',
            shadeClose: true,
            shade: 0.2,
            area: ['70%', '60%'],
            skin:'shangchuantup',
            content: '{:url("index/upload")}',
            shift:-1,
            scrollbar: false,
            moveType: 1,
            moveOut: true
        });
    })
</script>
</body>
</html>
